package com.orangelife.mobile.myhouse.biz;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;

import com.common.sp.CommSp2;
import com.common.sp.OtherSp;
import com.common.sp.UserSp;
import com.curry.android.http.OrangeDataHandler;
import com.curry.android.http.OrangeErrorHandler;
import com.curry.android.http.OrangeHttpConstant;
import com.curry.android.http.VolleyHttpUtil;
import com.datatrack.DataTrack;
import com.google.gson.reflect.TypeToken;
import com.common.jump.HouseJumper;
import com.orangelife.mobile.constants.CertURL;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.myhouse.activity.HouseTipActivity;
import com.orangelife.mobile.myhouse.entity.HouseBean;
import com.orangelife.mobile.myhouse.entity.IndustryBean;
import com.orangelife.mobile.myhouse.entity.IndustryEntity;
import com.orangelife.mobile.myhouse.entity.LocationBean;
import com.orangelife.mobile.myhouse.entity.ResidentBean;
import com.orangelife.mobile.myhouse.entity.ResidentBean2;
import com.orangelife.mobile.myhouse.entity.WaitCertEntity;
import com.orangelife.mobile.util.TimeUtil;
import com.orangelife.mobile.util.ToastHelper;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 房屋认证API
 * <p/>
 * Created by 吴格非 on 2015/11/11.
 */
public class HouseHttpBiz {

    /** 请求是否至少在一个小区有认证过 */
    public static void getHasCert() {
        VolleyHttpUtil.getInstance().getWithCallback(CertURL.HAS_CERT, new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject jsonObject, int i) {
                if (OrangeErrorHandler.getInstance().isSuccess(jsonObject,false)) {
                    Map<String, Object> map = OrangeDataHandler.getMapWithEntityNoGson(jsonObject);
                    if (map != null) {
                        String hasCert = String.valueOf(map.get("certification"));
                        UserSp.setHasCert(hasCert);
                        if (UserSp.hasCert()) {
                            OtherSp.setLastLoginID(UserSp.getLoginID());
                            UserSp.setCertName(String.valueOf(map.get("name")));
                        }
                    }
                }
            }
        });
    }

    public static void getHasCertInCurrentComm() {
        VolleyHttpUtil.getInstance().getWithCallback(CertURL.HAS_CERT_IN_CURRENT_COMM, new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject jsonObject, int i) {
                if (OrangeErrorHandler.getInstance().isSuccess(jsonObject,false)) {
                    Map<String, Object> map = OrangeDataHandler.getMapWithEntityNoGson(jsonObject);
                    if (map != null) {
                        String hasCert = String.valueOf(map.get("certification"));
                        UserSp.setHasCertInCurrentComm(hasCert);
                        OtherSp.setLastCommID(CommSp2.getCommID());
                        if(!hasCert.equals("0")) {
                            UserSp.setIdentity(String.valueOf(map.get("identity")));
                        }
                        DataTrack.identify();
                    }
                }
            }
        });
    }


    public static List handleCommonList(JSONObject response, Type type) {
        if (OrangeErrorHandler.getInstance().isSuccess(response)) {
            return OrangeDataHandler.getListFromJsonWithPageEntity(response, type, null, null);
        }
        return null;
    }

    /** 获取房屋列表 */
    public static void requestHouseList(VolleyHttpUtil.ResponseCallBack callback, int pageSize, int pageNo) {
        HashMap<String, String> map = new HashMap<>();
        map.put("pageIndex", String.valueOf(pageNo));
        map.put("pageSize", String.valueOf(pageSize));
        VolleyHttpUtil.getInstance().getWithCallback(CertURL.URL_HOUSE_LIST, map, callback);
    }

    @SuppressWarnings("unchecked")
    public static List<HouseBean> handleHouseList(JSONObject response) {
        return handleCommonList(response, new TypeToken<List<HouseBean>>() {
        }.getType());
    }

    /**
     * 认证成功之后，需要请求房屋列表，并保存到本地，用于投诉建议等模块，获取房屋信息
     * （当用户第一次认证的时候，若不保存，则其他模块无法获取房屋信息）
     * 获取本小区认证过的房屋，然后保存
     */
//    public static void getMyHousesListForSave() {
//        /*之所以不直接调用，因为这个公用方法在房屋认证这边是特殊用法，借用。而被两个地方调用，所以写成公用的*/
////        VolleyHttpUtil.getInstance().getWithHandler(CertURL.MY_HOUSE_LIST, new HouseHandler(), 123);
//        VolleyHttpUtil.getInstance().getWithCallback(CertURL.MY_HOUSE_LIST, new VolleyHttpUtil.ResponseCallBack() {
//            @Override
//            public void handleResponse(JSONObject jsonObject, int i) {
//                HouseHttpBiz.handleMyHouseList(jsonObject);
//            }
//        });
//    }

//    public static void handleMyHouseList(JSONObject result) {
//        if (OrangeErrorHandler.getInstance().isSuccess(result)) {
//            List<Map<String, String>> listMyHouse = OrangeDataHandler.getListFromJsonWithPageEntity(
//                    result, new TypeToken<List<Map<String, String>>>() {
//                    }.getType(), null, null);
//            boolean isVal = false;
//            String houseInfo = "";
//            if (listMyHouse != null && listMyHouse.size() != 0) {
//                isVal = true;
//            }
////            HouseBiz.setHasHouse(isVal);
//        }
//    }

    /** 获取房屋列表数量，直接取total */
//    public static void requestHouseListCount(VolleyHttpUtil.ResponseCallBack callback) {
//        requestHouseList(callback, 0, 1);
//    }

//    public static int handleHouseListCount(JSONObject response) {
//        int count = 0;
//        if (OrangeErrorHandler.getInstance().isSuccess(response)) {
//            String total = response.optString("total", "0");
//            try {
//                count = Integer.parseInt(total);
//            } catch (NumberFormatException e) {
//                e.printStackTrace();
//            }
//        }
//        return count;
//    }
    public static void synchOtherCertInfo(IndustryBean ib, VolleyHttpUtil.ResponseCallBack callback) {
        String URL_SYNCH_OTHER_CERT_INFO = Constant.URL_SYNCH_OTHER_CERT_INFO;
        HashMap<String, Object> jsonMap = new HashMap<>();
        jsonMap.put("certificationID", ib.getCertificationID());
        jsonMap.put("hasParkingSpace", ib.getHasParkingSpace());
        jsonMap.put("houseList", ib.getHouseList());
        VolleyHttpUtil.getInstance().postWithCallback(URL_SYNCH_OTHER_CERT_INFO, jsonMap, callback);
    }

    /** 提交户主或非户主的认证信息 */
    public static void commitCertInfo(VolleyHttpUtil.ResponseCallBack callback, ResidentBean rb) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("name", rb.getName());
        map.put("phone", rb.getPhone());
        map.put("identity", rb.getIdentity());
        map.put("code", rb.getCode());
        map.put("comID", rb.getCommID());
        VolleyHttpUtil.getInstance().postWithCallback(CertURL.URL_COMMIT_CERT_INFO, map, callback);
//        JsonLocalFileUtil.ogtest("HouseCertification",callback);
    }

    /** 判断用户是否在该小区认证过 */
//    public static void requestIsCert(String commID, VolleyHttpUtil.ResponseCallBack responseCallBack) {
//        HashMap<String, String> map = new HashMap<>();
////        map.put("commID", commID);
//        VolleyHttpUtil.getInstance().getWithCallback(HouseURL.isCert, map, responseCallBack);
//    }

//    public static Map<String, Object> handleIsCert(JSONObject response) {
//        Map<String, Object> map = new HashMap<>();
//        if (OrangeErrorHandler.getInstance().isSuccess(response, true)) {
//            map = OrangeDataHandler.getMapWithEntity(response);
//        }
//        return map;
//    }


    /**
     * HouseCert（业主认证）和HouseCode（非业主认证）都调用到这个方法
     *
     * @param response
     * @return 认证ID
     */
    public static IndustryBean handleCommitCertInfo(JSONObject response, Activity act, String errInfo) {
        IndustryBean ib = null;
        int errCode = OrangeErrorHandler.getInstance().getHttpErrorCode(response, errInfo, null);
        if (errCode == OrangeHttpConstant.RESULT_SUCCESS) {
//            certificationID = OrangeDataHandler.getValueListWithEntity(response, "certificationID").get(0);
            ib = (IndustryBean) OrangeDataHandler.getBeanWithEntity(response, IndustryBean.class);
            if (ib == null) {
                ToastHelper.getInstance()._toast("没有获取到数据...");
            }
        } else if (errCode == 71002) {/*提交的认证信息，审核失败*/
            try {
                Intent intent = new Intent(act, HouseTipActivity.class);
                intent.putExtra(HouseTipActivity.INTENT_KEY_HOUSE_TIP, HouseTipActivity.TYPE_TIP_INFO_ERROR);
                List<String> list = OrangeDataHandler.getValueListWithEntity(response, "phone");
                intent.putExtra("house_tip_value", response.getString("errInfo"));
                if (list != null && list.size() > 0) {
                    /*获取物业电话*/
                    intent.putExtra("house_tip_phone", list.get(0));
                }
                act.startActivity(intent);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return ib;
    }

    public static IndustryEntity handleCommitCertInfo2(JSONObject response, Context context, String errInfo) {
        IndustryEntity ib = null;
        int errCode = OrangeErrorHandler.getInstance().getHttpErrorCode(response, errInfo, null);
        if (errCode == OrangeHttpConstant.RESULT_SUCCESS) {
            ib = (IndustryEntity) OrangeDataHandler.getBeanWithEntity(response, IndustryEntity.class);
            if (ib == null) {
                ToastHelper.getInstance()._toast("没有获取到数据...");

                Map<String,Object> map=new HashMap<>();
                map.put("submitFailReason","没有获取到数据...");
                DataTrack.clickTrack("btnSubmit",map);
            }
        } else if (errCode == 71002) {/*提交的认证信息，审核失败*/
            handle71002(response, context);
        }
        return ib;
    }

    private static void handle71002(JSONObject response, Context context) {
        try {
            String info = response.getString("errInfo");
            String phone = "";
            List<String> list = OrangeDataHandler.getValueListWithEntity(response, "phone");
            if (list != null && list.size() > 0) {
                phone = list.get(0);
            }
            Map<String,Object> map=new HashMap<>();
            map.put("submitFailReason",info);
            DataTrack.clickTrack("btnSubmit",map);
            HouseJumper.jumpToOwnerCertFail(context, info, phone);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param callback
     * @param applicationID 申请ID
     * @param apartmentID   房屋ID
     * @param hostName      产权人名字
     * @param hostPhone     产权人电话
     */
    public static void commitTenantCert(String applicationID, String apartmentID, String hostName, String hostPhone, VolleyHttpUtil.ResponseCallBack callback) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("applicationID", applicationID);
        map.put("apartmentID", apartmentID);
        map.put("householderName", hostName);
        map.put("householderPhone", hostPhone);
        VolleyHttpUtil.getInstance().postWithCallback(CertURL.URL_COMMIT_TENANT_CERT, map, callback);
    }

    public static boolean handleTenantCert(JSONObject response, Context context, String errInfo) {
        int errCode = OrangeErrorHandler.getInstance().getHttpErrorCode(response, errInfo, null);
        if (errCode == OrangeHttpConstant.RESULT_SUCCESS) {
            return true;
        } else if (errCode == 71002) {/*提交的认证信息，审核失败*/
            Map<String,Object> map=new HashMap<>();
            map.put("submitFailReason","提交的认证信息，审核失败");
            DataTrack.clickTrack("btnSubmit",map);
            handle71002(response, context);
        }
        return false;
    }

    /** 获取待认证列表数量，直接取total */
    public static void requestWaitConfirmCount(VolleyHttpUtil.ResponseCallBack callback) {
        requestWaitConfirmList(callback, 1, 1, HouseBean.STATUS_ALL);
    }

    /** 保证至少会传回count */
    public static HashMap<String, String> handleWaitConfirmCount(JSONObject response) {
        HashMap<String, String> map = new HashMap<>();
        if (OrangeErrorHandler.getInstance().isSuccess(response)) {
            String total = response.optString("total", "0");
            map.put("count", total);
            if (!"0".equals(total)) {
                @SuppressWarnings("unchecked")
                List<HouseBean> list = (List<HouseBean>) handleCommonList(response, new TypeToken<List<HouseBean>>() {
                }.getType());
                if (list != null && list.size() == 1) {
                    map.put("certID", list.get(0).getLinkAptHouseholderID());
                    map.put("status", list.get(0).getIdentity());
                }
            }
        } else {
            map.put("count", "0");
        }
        return map;
    }

    /**
     * 获取待认证/已过期列表
     *
     * @param callback
     * @param pageSize
     * @param pageNo
     */
    public static void requestWaitConfirmList(VolleyHttpUtil.ResponseCallBack callback, int pageSize, int pageNo, String status) {
        HashMap<String, String> map = new HashMap<>();
        map.put("pageIndex", String.valueOf(pageNo));
        map.put("pageSize", String.valueOf(pageSize));
        map.put("status", status);
        VolleyHttpUtil.getInstance().getWithCallback(CertURL.URL_HOUSE_WAIT_CONFIRM, map, callback);
    }

    @SuppressWarnings("unchecked")
    public static List<WaitCertEntity> handleWaitConfirm(JSONObject response) {
        if (OrangeErrorHandler.getInstance().isSuccess(response)) {
            return (List<WaitCertEntity>) handleCommonList(response, new TypeToken<List<WaitCertEntity>>() {
            }.getType());
        }
        return null;
    }

    /**
     * 非户主提交验证码
     *
     * @param callback
     * @param applicationID 认证ID
     * @param code          验证码
     */
    public static void commitVerifyCode(VolleyHttpUtil.ResponseCallBack callback, String applicationID, String code) {
        HashMap<String, String> map = new HashMap<>();
        map.put("applicationID", applicationID);
        map.put("code", code);
        VolleyHttpUtil.getInstance().getWithCallback(CertURL.URL_HOUSE_COMMIT_HOST_CODE, map, callback);
    }


    /** 请求再次向户主发送验证码 */
    public static void requestHostCodeAgain(VolleyHttpUtil.ResponseCallBack callback, String applicationID) {
        HashMap<String, String> map = new HashMap<>();
        map.put("applicationID", applicationID);
        VolleyHttpUtil.getInstance().getWithCallback(CertURL.URL_HOUSE_REQUEST_HOST_CODE_AGAIN, map, callback);
    }

    /** 获取验证码有效时间 */
    public static void getCodeEffectTime(VolleyHttpUtil.ResponseCallBack callback, String applicationID) {
        HashMap<String, String> map = new HashMap<>();
        map.put("applicationID", applicationID);
        VolleyHttpUtil.getInstance().getWithCallback(CertURL.URL_HOUSE_GET_CODE_TIME, map, callback);
    }

    public static String handleCodeEffectTime(JSONObject response) {
        String time = "...";
        if (OrangeErrorHandler.getInstance().isSuccess(response)) {
            ArrayList<String> list = OrangeDataHandler.getValueListWithEntity(response, "overdate");
            if (list != null && list.size() > 0) {
                try {
                    long t = Long.parseLong(list.get(0));
                    time = TimeUtil.timeStampToDate(t, "yyyy年MM月dd日 HH点mm分");
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }
        }
        return time;
    }

    /** 获取回填数据 */
//    public static void getHasCert(VolleyHttpUtil.ResponseCallBack callback) {
//        VolleyHttpUtil.getInstance().getWithCallback(CertURL.URL_HOUSE_HAS_CERT, callback);
//    }

//    public static Map<String, Object> handleHouseInfoWhenReFill(JSONObject response) {
//        Map<String, Object> map = null;
//        if (OrangeErrorHandler.getInstance().isSuccess(response)) {
//            map = OrangeDataHandler.getMapWithEntity(response);
//        }
//        return map;
//    }

    /** 邀请新住户 */
    public static void requestInvite(VolleyHttpUtil.ResponseCallBack callback, String linkAptHouseholderID, String tel) {
        if (linkAptHouseholderID == null) {
            ToastHelper.getInstance()._toast("产权业主关联ID错误");
            return;
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("linkAptHouseholderID", linkAptHouseholderID);
        map.put("phone", tel);
        VolleyHttpUtil.getInstance().getWithCallback(CertURL.URL_HOUSE_INVITE, map, callback);
    }

    /** 获取住户列表 */
    public static void getResidentList(VolleyHttpUtil.ResponseCallBack callback, String apartmentID, String identity, int pageSize, int pageNo) {
        HashMap<String, String> map = new HashMap<>();
        map.put("apartmentID", apartmentID);
        map.put("identity", identity);
        map.put("pageIndex", String.valueOf(pageNo));
        map.put("pageSize", String.valueOf(pageSize));
        VolleyHttpUtil.getInstance().getWithCallback(CertURL.URL_HOUSE_RESIDENT_LIST, map, callback);
    }

    public static List<ResidentBean2> handleResidentList(JSONObject response) {
        List<ResidentBean2> list = null;
        if (OrangeErrorHandler.getInstance().isSuccess(response)) {
            list = OrangeDataHandler.getListFromJsonWithPageEntity(response, new TypeToken<List<ResidentBean2>>() {
            }.getType(), null, null);
        }
        return list;
    }

    public static void getResidentDetail(String linkAptHouseholderID, VolleyHttpUtil.ResponseCallBack callback) {
        HashMap<String, String> map = new HashMap<>();
        map.put("linkAptHouseholderID", linkAptHouseholderID);
        VolleyHttpUtil.getInstance().getWithCallback(CertURL.RESIDENT_DETAIL, map, callback);
    }

    public static Map<String, Object> handleResidentDetail(JSONObject response) {
        Map<String, Object> map = null;
        if (OrangeErrorHandler.getInstance().isSuccess(response)) {
            map = OrangeDataHandler.getMapWithEntity(response);
        }
        return map;
    }

    /** 删除住户 */
    public static void delResident(VolleyHttpUtil.ResponseCallBack callback, String linkAptHouseholderID) {
        HashMap<String, String> map = new HashMap<>();
        map.put("linkAptHouseholderID", linkAptHouseholderID);
        VolleyHttpUtil.getInstance().delWithCallback(CertURL.URL_HOUSE_DEL_RESIDENT, map, callback);
    }

    /** 删除已过期的待认证 */
    public static void delExpireUser(VolleyHttpUtil.ResponseCallBack callback, String applicationID) {
        HashMap<String, String> map = new HashMap<>();
        map.put("applicationID", applicationID);
        VolleyHttpUtil.getInstance().delWithCallback(CertURL.URL_HOUSE_DEL_EXPIRE_RESIDENT, map, callback);
    }

    /**
     * 获取位置列表
     *
     * @param callback
     * @param cityName 请求小区列表的时候，需要城市名，请求方式与其他三种不同
     * @param url      城市、小区、楼栋、房号的URL
     */
    public static void getLocationList(VolleyHttpUtil.ResponseCallBack callback, String cityName, String url) {
        if (cityName == null) {
            VolleyHttpUtil.getInstance().getWithCallback(url, callback);
        } else {
            HashMap<String, String> map = new HashMap<>();
            map.put("cityName", cityName);
            VolleyHttpUtil.getInstance().getWithCallback(url, map, callback);
        }
    }

    public static List handleLocationList(JSONObject response) {
        if (OrangeErrorHandler.getInstance().isSuccess(response)) {
            return OrangeDataHandler.getListFromJsonWithPageEntity(response, new TypeToken<List<LocationBean>>() {
            }.getType(), null, null);
        }
        return null;
    }
}
